import axios from 'axios'
import { ElMessage } from 'element-plus'

const service = axios.create({
  baseURL: 'http://localhost:8080/api',
  timeout: 5000
})

// Request interceptor
service.interceptors.request.use(
  config => {
    const userInfo = JSON.parse(localStorage.getItem('user') || '{}')
    if (userInfo.token) {
      config.headers['Authorization'] = `Bearer ${userInfo.token}`
    }
    return config
  },
  error => {
    console.error(error)
    return Promise.reject(error)
  }
)

// Response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    
    if (res.code !== 200) {
      ElMessage({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      
      if (res.code === 401) {
        // Handle token expiration
        localStorage.removeItem('user')
        location.href = '/login'
      }
      
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.error('API Error:', error)
    ElMessage({
      message: error.message || 'Request Error',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service 